<template>
  <div>
    <div class="firstBox app-container">
      <el-form :model="queryParams" ref="queryRef" inline label-width="100px">
        <el-form-item label="搜索老师：" prop="wxParam">
          <el-input
            v-model="queryParams.wxParam"
            placeholder="请输入老师姓名/手机号"
            clearable
            style="width: 240px"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleTeacherQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetTeacherQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" border :data="teacherTableDatas">
        <el-table-column label="序号" width="55" align="center">
          <template #default="scope">
            <span>{{
              (queryParams.pageNum - 1) * queryParams.pageSize +
              scope.$index +
              1
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="老师姓名" align="center" prop="nickName">
          <template #default="scope">
            <router-link
              :to="'/registrar/teacherDetails/detail/' + scope.row.id"
              class="link-type"
            >
              <div style="display: flex; align-items: center">
                <span
                  style="margin-right: 10px; color: #67c23a; cursor: pointer"
                  >{{ scope.row.nickName }}</span
                >
              </div>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column
          label="手机号"
          align="center"
          prop="mobile"
        ></el-table-column>
        <el-table-column label="性别" align="center" prop="gender">
          <template #default="scope">
            <div>
              {{
                sys_user_sex.filter((val) => val.value == scope.row.gender)[0]
                  .label
              }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="上月课时"
          align="center"
          prop="yh"
        ></el-table-column>
        <el-table-column
          label="本月课时"
          align="center"
          prop="nh"
        ></el-table-column>
        <el-table-column
          label="已上课时"
          align="center"
          prop="ah"
        ></el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="300"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="Edit"
              v-hasPermi="['institution:staff:edit']"
              @click="handleUpdateTeacher(scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="teacherTotal > 0"
        :total="teacherTotal"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getTeacherList"
      />
    </div>
    <!-- 修改老师 -->
    <el-drawer
      v-model="teacherOpen"
      title="编辑老师"
      :width-header="true"
      size="50%"
      :close-on-click-modal="false"
    >
      <div class="content">
        <el-form
          ref="teacherFormRef"
          :model="teacherForm"
          label-width="100px"
          label-suffix=" :"
        >
          <el-form-item
            label="登陆账号"
            prop="name"
            :rules="[
              {
                required: true,
                message: '请输入登陆账号',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model="teacherForm.name"
              placeholder="请输入登陆账号"
              style="width: 300px"
              clearable
            ></el-input
          ></el-form-item>
          <el-form-item
            label="员工姓名"
            prop="nickName"
            :rules="[
              {
                required: true,
                message: '请输入员工姓名',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model="teacherForm.nickName"
              placeholder="请输入员工姓名"
              style="width: 300px"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="手机号"
            prop="mobile"
            :rules="[
              {
                required: true,
                message: '请输入正确得手机号',
                trigger: 'blur',
                pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              },
            ]"
          >
            <el-input
              v-model="teacherForm.mobile"
              placeholder="请输入手机号"
              clearable
              style="width: 300px"
            ></el-input>
          </el-form-item>
          <el-form-item style="margin-top: -10px"
            ><div style="color: #aaa">
              此手机号将作为员工登录系统的账号，初始密码：123456
            </div></el-form-item
          >
          <el-form-item label="性别">
            <el-radio-group v-model="teacherForm.gender">
              <el-radio
                v-for="dict in sys_user_sex"
                :key="dict.value"
                :value="dict.value"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <!-- <el-form-item label="是否在职" prop="isJob">
            <el-switch
              v-model="teacherForm.isJob"
              :active-value="true"
              :inactive-value="false"
              @change="handleIsJobChange"
            ></el-switch>
          </el-form-item> -->
          <el-form-item label="是否授课" prop="isTeach">
            <el-switch
              v-model="teacherForm.isTeach"
              :active-value="true"
              :inactive-value="false"
              @change="handleIsTeachChange"
            ></el-switch>
          </el-form-item>
          <el-form-item style="margin-top: -10px"
            ><div style="color: #aaa">
              开启后，该员工将出现在老师管理，可为该员工进行上课安排
            </div></el-form-item
          >
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="teacherForm.remark"
              style="width: 300px"
              :rows="4"
              type="textarea"
              placeholder="请输入备注"
            />
          </el-form-item>
          <el-form-item label="所属角色">
            <div>选择角色后，下方将显示对应的权限。</div>
          </el-form-item>
          <el-form-item prop="roleIds">
            <div style="display: flex; flex-wrap: wrap">
              <div
                v-for="item in staffRoleList"
                :key="item.orgId"
                :class="[
                  'staffRoleItem',
                  selectRoles.indexOf(item.roleId) !== -1
                    ? 'selectStaffRole'
                    : '',
                ]"
                @click="handleChooseRole(item)"
              >
                <div style="display: flex; align-items: center">
                  <div
                    style="
                      background-color: #2f90ea;
                      text-align: center;
                      width: 30px;
                      height: 30px;
                      line-height: 30px;
                      border-radius: 15px;
                    "
                  >
                    <el-icon color="#fff" :size="16" style="margin-top: 6px">
                      <Avatar />
                    </el-icon>
                  </div>
                  <div
                    class="ml10"
                    style="
                      color: #333;
                      white-space: nowrap;
                      overflow: hidden;
                      text-overflow: ellipsis;
                    "
                  >
                    {{ item.roleName }}
                  </div>
                  <div class="customStyle" v-if="item.orgId != 1">自定义</div>
                </div>
                <div style="color: #999">{{ item.remark }}</div>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="teacherOpen = false">取消</el-button>
        <el-button type="primary" @click="submitTeacherForm"> 保存 </el-button>
      </template>
    </el-drawer>
  </div>
</template>
<script setup name="Teacher">
import { onMounted, reactive, ref, toRefs, nextTick } from "vue";
import { getTeacherEmployeesApi } from "@/api/registrar/teacher.js";
import {
  getStaffRolesApi,
  getStaffInfoApi,
  updateStaffApi,
} from "@/api/institution/staff";

const { proxy } = getCurrentInstance();

const loading = ref(false);
const teacherTableDatas = ref([]);
const teacherTotal = ref(0);
const { sys_user_sex } = proxy.useDict("sys_user_sex");

// 编辑老师
const teacherOpen = ref(false);
const staffRoleList = ref([]); // 员工角色列表
const selectRoles = ref([]); // 选中角色集合

const data = reactive({
  queryParams: {
    wxParam: "",
    pageNum: 1,
    pageSize: 10,
  },
  teacherForm: {
    id: "",
    name: "", // 登陆账号
    nickName: "", // 员工姓名
    gender: "0", // 性别 0： 男， 1： 女
    mobile: "", // 手机号
    isTeach: false, // 是否授课
    isJob: true, // 在职
    remark: "", // 备注
    roleIds: "",
  },
});

const { queryParams, teacherForm } = toRefs(data);

// 获取列表
const getTeacherList = async () => {
  loading.value = true;
  const { total, rows } = await getTeacherEmployeesApi(queryParams.value);
  console.log("t: ", total, rows);
  teacherTableDatas.value = rows;
  teacherTotal.value = total;
  loading.value = false;
};

// 搜索
const handleTeacherQuery = () => {
  queryParams.value.pageNum = 1;
  getTeacherList();
};

// 重置
const resetTeacherQuery = () => {
  proxy.resetForm("queryRef");
  handleTeacherQuery();
};

// 重置员工新增表单
const resetTeacher = () => {
  teacherForm.value = {
    id: "",
    name: "", // 登陆账号
    nickName: "", // 员工姓名
    gender: "0",
    mobile: "", // 手机号
    isJob: true, // 在职
    isTeach: false, // 是否授课
    remark: "", // 备注
    roleIds: "",
  };
  proxy.resetForm("teacherFormRef");
};

// 编辑
const handleUpdateTeacher = (row) => {
  resetTeacher();
  const userId = row.id;
  getStaffInfoApi(userId).then((res) => {
    teacherOpen.value = true;
    teacherForm.value = res.data;
    teacherForm.value.gender = teacherForm.value.gender.toString();
    selectRoles.value = res.roleIds;
  });
};

// 获取员工角色列表
const getStaffRoles = async () => {
  const { roles } = await getStaffRolesApi();
  staffRoleList.value = roles;
};

// 员工新增选择角色
const handleChooseRole = async (item) => {
  if (selectRoles.value.indexOf(item.roleId) !== -1) {
    // 取消选中
    selectRoles.value = selectRoles.value.filter((val) => val !== item.roleId);
  } else {
    selectRoles.value.push(item.roleId);
  }
};

// 是否授课
const handleIsTeachChange = (value) => {
  teacherForm.value.isTeach = value;
};

// 是否在职
const handleIsJobChange = (value) => {
  teacherForm.value.isJob = value;
};

// 员工新增提交
const submitTeacherForm = () => {
  proxy.$refs["teacherFormRef"].validate((valid) => {
    if (valid) {
      if (teacherForm.value.id != undefined && teacherForm.value.id != "") {
        // 修改
        updateStaffApi({
          ...teacherForm.value,
          roleIds: selectRoles.value.join(","),
        }).then((res) => {
          proxy.$modal.msgSuccess("修改成功");
          teacherOpen.value = false;
          getTeacherList();
        });
      }
    }
  });
};

// 初始化请求
onMounted(async () => {
  // 获取员工列表
  await getTeacherList();
  // 获取角色
  await getStaffRoles();
});
</script>
<style lang="scss" scoped>
@import "@/assets/styles/variables.module.scss";
.staffRoleItem {
  width: 230px;
  height: 150px;
  border-radius: 10px;
  border: 1px solid #eee;
  margin-right: 20px;
  margin-bottom: 20px;
  padding: 15px;
  box-sizing: border-box;
  cursor: pointer;
}

.selectStaffRole {
  border-color: $--color-primary;
}

.customStyle {
  width: 50px;
  height: 24px;
  border-radius: 5px;
  line-height: 24px;
  border: 1px solid $--color-primary;
  text-align: center;
  font-size: 12px;
  margin-left: 10px;
}
</style>